import 'package:util/result/result.dart';

extension ResultExtension<T> on Result<T> {
  bool get isOk => this is Ok<T>;

  bool get isError => this is Error<T>;

  void throwOnError() {
    if (isError) {
      throw (this as Error<T>).error;
    }
  }

  Result<T> onOk(Function(T) action) {
    if (isOk) {
      action((this as Ok<T>).value);
    }

    return this;
  }

  Result<T> onError(Function(Exception) action) {
    if (isError) {
      action((this as Error<T>).error);
    }
    return this;
  }

  T? getOrNull() {
    if (this.isOk) {
      return (this as Ok<T>).value;
    }
    return null;
  }

  Exception? exceptionOrNull() {
    if (this.isError) {
      return (this as Error<T>).error;
    }
    return null;
  }
}
